// web/src/components/auth/new-verification-form.tsx
'use client';
import React, {useCallback, useEffect, useState} from 'react';
import CardWrapper from "@/components/auth/card-wrapper";
import {BeatLoader} from "react-spinners";
import {useSearchParams} from "next/navigation";
import {newVerification} from "@/actions/new-verification";
import FormError from "@/components/form-error";
import FormSuccess from "@/components/form-success";

const NewVerificationForm = () => {
    const searchParams = useSearchParams()
    const token = searchParams.get('token')

    const [error, setError] = useState<string | undefined>()
    const [success, setSuccess] = useState<string | undefined>()

    const onSubmit = useCallback(() => {
        if (success || error) return
        if (!token) {
            setError('Missing token!')
            return
        }

        newVerification(token)
            .then((data) => {
                setSuccess(data.success)
                setError(data.error)
            })
            .catch(() => {
                setError('Something went wrong!')
            })
    }, [token, success, error])

    useEffect(() => {
        onSubmit()
    }, [onSubmit])

    return (
        <CardWrapper
            headerLabel={'Confirm your verification'}
            backButtonLabel={'Back to login'}
            backButtonHref={'/auth/login'}
        >
            <div className={`flex items-center w-full justify-center`}>
                {/*
                由于开发模式+react严格模式导致渲染两次
                所以会先显示成功, 再显示失败
                */}
                {!success && !error && <BeatLoader/>}
                <FormSuccess message={success}/>
                {!success && <FormError message={error}/>}
            </div>
        </CardWrapper>
    );
};

export default NewVerificationForm;